<template>
  <div class="app-container">
    <div class="header">
      <div
        class="filter-container"
        style="padding-bottom: 30px;width: calc(100% - 360px);display: inline-block; margin-top: 28px"
      >

        <el-input
          v-model="kwInput"
          placeholder="输入内容进行筛选"
          class="input-with-select"
          clearable
          @keyup.native.enter="handleSearch"
        >
          <el-select slot="prepend" v-model="selected_product" placeholder="产品" multiple collapse-tags>
            <el-option
              v-for="item in products"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-button slot="append" icon="el-icon-search" :disabled="!searchAvailable" @click="handleSearch">搜索
          </el-button>
        </el-input>
      </div>
      <div style="display: inline-block; margin-left: 50px">

        <el-button
          type="primary"
          class="el-icon-plus add-btn"
          @click="handleAction('create', {'type': 'product', 'name': '单个添加产品'}, 'product')"
        >单个添加产品
        </el-button>
        <el-button
          type="warning"
          class="el-icon-plus add-btn"
          @click="handleAction('create', {'type': 'image', 'name': '批量添加产品', 'catalog_id': c_id }, 'product__multi')"
        >
          批量添加产品
        </el-button>
      </div>
    </div>

    <div style="float: right; margin-right: 8px;margin-bottom: 5px">
      <el-button size="mini" type="warning" :disabled="!productSelected.length" @click="handleEditProductAttr(productSelected)">修改选中项 产品模版属性
      </el-button>
    </div>

    <tree-table
      v-loading="treeLoading"
      :data="data"
      :eval-func="func"
      :expand-all="expandAll"
      border
      fit
      highlight-current-row
      style="width: 100%"
      element-loading-text="给我一点时间"
      @handleSelectionChange="handleSelectionChange($event)"
    >

      <el-table-column label="图片数量" align="center" prop="image__count" width="78" />

      <el-table-column label="信息" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.type === 'product'"><span><el-tag
            v-for="t in scope.row.tag"
            :key="t"
            class="mt-tag"
            size="mini"
            type="success"
          >{{ t }}</el-tag>{{ scope.row.tag.length?' | ': '' }}原价:{{ scope.row.original_price }}</span>
          </div>

          <img
            v-else-if="scope.row.url"
            :src="scope.row.url"
            class="img img-thumbnail"
            @click="handleViewImage(scope.row.url)"
          >
        </template>
      </el-table-column>

      <el-table-column label="操作" width="440" align="center" class-name="small-padding fiexed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleAction('view', scope.row)">查看</el-button>
          <el-button size="mini" type="success" plain @click="handleAction('edit', scope.row)">修改</el-button>
          <el-button size="mini" type="danger" plain @click="handleAction('delete', scope.row)">删除</el-button>
          <el-button
            v-if="scope.row.type==='product'"
            size="mini"
            type="primary"
            plain
            @click="handleAction('create', scope.row, 'image')"
          >添加图片
          </el-button>

          <el-button
            v-if="scope.row.type==='product'"
            type="warning"
            size="mini"
            icon="el-icon-setting"
            @click="handleEditProductAttr(scope.row)"
          >模版属性
          </el-button>
          <el-button
            v-if="scope.row.type==='image'"
            type="success"
            size="mini"
            @click="handleImageMain(scope.row.id)"
          >设为主图
          </el-button>
        </template>
      </el-table-column>
    </tree-table>

    <el-pagination
      v-if="data.length"
      background
      class="mt-pagination"
      :current-page="page"
      :page-sizes="[10,20,50,100]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />

    <product
      :model="product_form_data"
      :action="productAction"
      :dialog-title="dialogTitle"
      :dialog-form-visible="productFormVisible"
      @reload="reload"
      @cancelDialog="cancelProductDialog($event)"
    />

    <mt_image
      :model="image_form_data"
      :action="imageAction"
      :dialog-title="dialogTitle"
      :dialog-form-visible="imageFormVisible"
      @reload="reload"
      @cancelDialog="cancel_imageDialog($event)"
    />

    <product-attr
      :model="productAttrForm"
      :product_id="currentProductId"
      :template-dialog-visible="productAttrDialogVisible"
      @reload="getList"
      @cancelProductAttrDialog="cancelProductAttrDialog($event)"
    />

  </div>
</template>

<script>
import treeTable from '@/components/TreeTable'
import treeToArray from './treeTable/customEval'
import product from './elements/product'
import mt_image from './elements/image'

import { GetTree, Get } from '@/api/erp/elicink/product'
import { imageMain } from '@/api/erp/elicink/image'
import productAttr from './elements/productAttr'

const qs = require('qs')
const axios = require('axios')

const MtTypeOptions = {
  product: '产品',
  image: '图片'
}

export default {
  name: 'ProdutManage',
  components: { product, treeTable, mt_image, productAttr },
  data() {
    return {
      dialogTitle: '',

      // product dialog
      product_form_data: null,
      productFormVisible: false,
      productAction: null,

      // mt_image dialog
      image_form_data: {},
      imageFormVisible: false,
      imageAction: null,

      // 产品 选择器 数据源
      products: [],

      // input
      kwInput: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,
      searchAvailable: true,
      // 选中的 产品id
      selected_product: [],
      // talbe 数据源
      data: [],
      // table loading
      treeLoading: false,
      MtTypeOptions,
      func: treeToArray,
      expandAll: false,

      // 修改产品属性
      currentProductId: null,
      productAttrForm: {}, // 当前 product row 模版编辑表单内容
      productAttrDialogVisible: false,

      // 修改选中项 产品模版属性
      productSelected: [],
      // 默认属性
      defaultAttr: []
    }
  },
  computed: {
    c_id: function() {
      return this.$route.params.c_id
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      if (!this.c_id) {
        this.$router.push({ path: '/' })
      }
      this.treeLoading = true

      axios.all([
        GetTree(this.c_id, qs.stringify({
          kw: this.kwInput,
          pagesize: this.pagesize,
          page: this.page
        })),
        Get(null, qs.stringify({ c_id: this.c_id }))
      ])
        .then(axios.spread((tree, products) => {
          this.data = tree.data
          this.total = tree.total
          this.defaultAttr = tree.attr
          this.products = products.data.data
          this.treeLoading = false
          this.searchAvailable = true
        })).catch(e => {
          this.treeLoading = false
          this.searchAvailable = true
        })
    },
    handleAction(action, row, _) {
      switch (action) {
        case 'delete':
          this.dialogTitle = ['确认要删除 [', MtTypeOptions[row.type], '] ', row.name || row.title, ' 的所有内容?'].join('')
          break
        case 'view':
          this.dialogTitle = ['查看 ', MtTypeOptions[row.type], ' —— ', row.name || row.title].join('')
          break
        case 'edit':
          this.dialogTitle = ['修改 ', MtTypeOptions[row.type], ' —— ', row.name || row.title].join('')
          break
        case 'create':/* 特殊处理, 根据 _ 判断行为 */
          if (_ === 'product') {
            this.dialogTitle = '添加产品'
            this.productAction = action
            this.productFormVisible = true
            this.product_form_data = row
          } else if (_ === 'image') {
            this.dialogTitle = '添加图片'
            this.imageAction = action
            this.imageFormVisible = true
            this.image_form_data = row
          } else if (_ === 'product__multi') {
            this.dialogTitle = '批量添加产品'
            this.imageAction = action
            this.imageFormVisible = true
            this.image_form_data = row
          }
          return
      }
      switch (row.type) {
        case 'product':
          this.productAction = action
          this.productFormVisible = true
          this.product_form_data = row
          break
        case 'image':
          this.imageAction = action
          this.imageFormVisible = true
          this.image_form_data = row
          break
      }
    },
    cancelProductDialog(v) {
      this.productFormVisible = v
    },
    cancel_imageDialog(v) {
      this.imageFormVisible = v
    },
    reload() {
      this.getList()
    },
    toUpload(cid) {
      this.$router.push({ path: '/elicink/product' })
    },
    handleViewImage(v) {
      if (v) window.open(v)
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    // productAttr form dialog 隐藏
    cancelProductattrDialog(v) {
      this.productAttrDialogVisible = v
    },
    // 修改 模版属性
    handleEditProductAttr(row) {
      if (row.attr) {
        this.productAttrDialogVisible = true
        this.productAttrForm = row.attr
        this.currentProductId = row.id
      }
      if (row.length) {
        this.productAttrDialogVisible = true
        this.productAttrForm = this.defaultAttr
        this.currentProductId = row.map(v => v.id)
      }
    },
    // 设定为 ImageMain
    handleImageMain(id) {
      imageMain(id).then(response => {
        this.getList()
      })
    },
    // 处理选中项目
    handleSelectionChange(v) {
      this.productSelected = v
    },
    // productAttr form dialog 隐藏
    cancelProductAttrDialog(v) {
      this.productAttrDialogVisible = v
    }
  }
}
</script>

<style scoped>
  .mt-tag {
    margin-left: 5px;
  }

  .filter-container >>> .el-select .el-input {
    width: 350px;
  }

  .filter-container >>> .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }

  .filter-container >>> .el-input-group__append .el-button--default {
    color: white;
    background-color: #409EFF;
    border: 1px solid #409eef;
  }

  .img-thumbnail {
    border-color: #ccc !important;

    padding: 4px;
    line-height: 1.42857;
    border-radius: 3px;
    -webkit-transition: all 0.2s ease-in-out;
    -o-transition: all 0.2s ease-in-out;
    transition: all 0.2s ease-in-out;
    display: inline-block;

    width: 90px
  }

  .mt-pagination {
    float: right;
    margin-top: 5px;
  }

  .app-container >>> span.el-tag--info {
    word-break: normal;
    width: auto;
    display: block;
    white-space: pre-wrap;
    word-wrap: break-word;
    overflow: hidden;
  }
</style>
